import {KoaMiddlewareInterface, Middleware} from "routing-controllers";

@Middleware({type: "before"})
export class SendMiddleware implements KoaMiddlewareInterface {
  async use(ctx: any, next: (err?: any) => Promise<any>): Promise<any> {
      ctx.state.send = this.render(ctx);
      ctx.state.sendError = this.renderError(ctx);
      return next();
  }

  // 处理请求成功方法
  render(ctx: any) {
    return (data:object = {}, msg:string =  '请求成功',code:number = 200) => {
      ctx.response.status = 200
     return ctx.response.body = {
        code,
        data,
        msg
      }
    }
  }

  // 处理请求失败方法
  renderError(ctx: any) {
    return (code: number, msg = '请求失败') => {
      ctx.set('Content-Type', 'application/json');
      ctx.response.status = 200
      ctx.response.body = {
        code,
        data: null,
        msg
      }
    }
  }
}
